﻿using System;
using EvaluationSystem.Dto;
using EvaluationSystem.Models;
using EvaluationSystem.Utils;
using EvaluationSystem.ViewModels;

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace EvaluationSystem.Controllers
{
    public class TeacherController : BaseController<TeacherController>
    {
        public TeacherController(ILogger<TeacherController> logger, MyDbContext dbContext) : base(logger, dbContext)
        {
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns> 
        public IActionResult Index([FromQuery] PageDto pageDto)
        {
            // 获取用户信息
            GetUserToken<People>(out var people);

            // 获取评价信息
            var pageDataVm = pageDto.GetAutoPageList<StudentEvalCourse>(people, () => _dbContext.StudentCourse
                .Include(t => t.TeacherWithCourses)
                .ThenInclude(t => t.Course)
                .Include(t => t.Student)
                .Where(t => t.TeacherWithCourses!.TeacherId == people.PeopleId)
                .OrderByDescending(t => t.Score)
                .ThenByDescending(t => t.CreatedAt));

            // 返回页面
            return View(pageDataVm);
        }

        /// <summary>
        /// 评价页
        /// </summary>
        /// <param name="scId"></param>
        /// <returns></returns>
        public async Task<IActionResult> Result([FromQuery] int scId)
        {
            GetUserToken<People>(out var person);
            if (scId > 0)
            {
                StudentEvalCourse? sec = await _dbContext.StudentCourse.FirstOrDefaultAsync(x => x.ScId == scId);
                var text = sec?.Evals;
                var ques = await _dbContext.Claim.ToListAsync();
                List<QuesInfoVM> qinfos = ScoreUtil.GetQuesInfos(text, ques);
                if (qinfos.Count == 0)
                {
                    return RedirectToAction("Index");
                }

                var vm = new EvalResultVM
                {
                    People = person,
                    QuesInfos = qinfos,
                    IsEvaluate = true,
                    Score = sec?.Score,
                };
                var comments = await _dbContext.Comment
                    .Include(t => t.Publisher)
                    .Include(t => t.Replier)
                    .OrderByDescending(t => t.CreatedAt)
                    .Where(t => t.ScId == scId)
                    .Select(t => new CommentVm(t))
                    .ToListAsync();
                vm.Comments = comments;
                return View(vm);
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        #region Course

        /// <summary>
        /// 课程信息页面
        /// </summary>
        /// <param name="pageDto"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Course([FromQuery] PageDto pageDto, [FromQuery] int? id)
        {
            // 获取用户信息
            GetUserToken<People>(out var people);

            // 删除操作
            if (id.HasValue)
            {
                var course = await _dbContext.Course.FirstAsync(t => t.CourseId == id);
                _dbContext.Entry(course).State = EntityState.Deleted;
                var num = await _dbContext.SaveChangesAsync();
                ViewData["msg"] = num > 0 ? "删除成功" : "删除失败";
            }

            // 获取评价信息
            var pageDataVm = pageDto.GetAutoPageList<TeacherWithCourse>(people, () => _dbContext.TeacherCourse.OrderByDescending(t => t.CreatedAt)
                .Include(t => t.Course)
                .Where(t => t.TeacherId == people.PeopleId));
            pageDataVm.RouteInfoVM = new RouteInfoVM("Course", "Teacher");

            // 返回页面
            return View(pageDataVm);
        }

    
        [HttpPost("Course/Add")]
        public async Task<IActionResult> AddCourse([FromForm] Course course)
        {
            // 获取用户信息
            GetUserToken<People>(out var people);
            int num = 0;
            using (var trans = await _dbContext.Database.BeginTransactionAsync())
            {
                try
                {
                    var c_entity = await _dbContext.Course.AddAsync(course);
                    num = await _dbContext.SaveChangesAsync();
                    if (num > 0)
                    {
                        var tc_entity = await _dbContext.TeacherCourse.AddAsync(new TeacherWithCourse()
                        {
                            CourseId = c_entity.Entity.CourseId,
                            TeacherId = people.PeopleId,
                        });
                        num = await _dbContext.SaveChangesAsync();
                    }
                    else
                    {
                        await trans.RollbackAsync();
                    }
                    await trans.CommitAsync();
                }
                catch (Exception ex)
                {
                    await trans.RollbackAsync();
                    throw;
                }

            }

            return Ok(ResultDto.Ok(num > 0 ? "添加成功" : "添加失败"));
        }

        [HttpDelete("Course/Delete")]
        public async Task<IActionResult> DeleteCourse([FromQuery] int id)
        {
            if (id > 0)
            {
                int num = 0;
                var tc_entity = await _dbContext.TeacherCourse.FirstOrDefaultAsync(t => t.TcId == id);
                if (tc_entity != null)
                {
                    using (var trans = await _dbContext.Database.BeginTransactionAsync())
                    {
                        try
                        {
                            _dbContext.Entry(tc_entity).State = EntityState.Deleted;
                            _dbContext.TeacherCourse.Remove(tc_entity);
                            _dbContext.Course.Remove(new Course() { CourseId = tc_entity.CourseId });
                            num = await _dbContext.SaveChangesAsync();
                            await trans.CommitAsync();
                        }
                        catch (Exception ex)
                        {
                            await trans.RollbackAsync();
                            throw;
                        }
                    }
                }

                return Ok(ResultDto.Ok(num > 0 ? "删除成功" : "删除失败"));
            }
            else
            {
                return Ok(ResultDto.Fail(msg: "参数错误"));
            }
        }

        #endregion


        /// <summary>
        /// 导出excel
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Export()
        {
            if (GetUserToken<People>(out People person))
            {
                // 获取评价信息
                if (person != null)
                {
                    IList<EvalInfoExcelVM> list = GetEvalInfos(person.PeopleId);

                    var filename = $"{Guid.NewGuid()}.xlsx";
                    var path = WriteExcel(list, filename);
                    var s = await System.IO.File.ReadAllBytesAsync(path);
                    return File(s, "application/vnd.ms-excel", filename);
                }

                {
                    return Ok(Dto.ResultDto.Fail(msg: "没有获取用户信息"));
                }
            }
            else
                return RedirectToAction("Index");
        }

        /// <summary>
        /// 写入到excel里并返回保存的路径
        /// </summary>
        /// <param name="list"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        string WriteExcel(IList<EvalInfoExcelVM>? list, string filename)
        {
            // NPOI
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("评价表");
            //创建行

            // 写头部
            {
                IRow row = sheet.CreateRow(0); //i表示了创建行的索引，从0开始
                row.CreateCell(0).SetCellValue("学生id");
                row.CreateCell(1).SetCellValue("学生名");
                row.CreateCell(2).SetCellValue("课程名");

                int col = 3;
                var evals = list?[0].Evals;
                if (evals != null)
                    foreach (var item in evals)
                    {
                        row.CreateCell(col).SetCellValue(item.Key);
                        col++;
                    }
            };

            int rowIndex = 1;
            if (list != null)
                foreach (var item in list)
                {
                    IRow row = sheet.CreateRow(rowIndex); //i表示了创建行的索引，从0开始
                    row.CreateCell(0).SetCellValue(item.StudentID);
                    row.CreateCell(1).SetCellValue(item.StudentName);
                    row.CreateCell(2).SetCellValue(item.CourseName);

                    int col = 3;
                    foreach (var ite in item.Evals)
                    {
                        row.CreateCell(col).SetCellValue(ite.Value);
                        col++;
                    }

                    rowIndex++;
                }

            //表格制作完成后，保存
            //创建一个文件流对象
            //var path = Path.Combine(Path.GetTempPath(), filename);
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename);
            using (FileStream fs = System.IO.File.Open(path, FileMode.OpenOrCreate))
            {
                workbook.Write(fs);
                //最后记得关闭对象
                workbook.Close();
            }

            return path;
        }

        IList<EvalInfoExcelVM> GetEvalInfos(int tid)
        {
            var es = _dbContext.Excel_View.Where(t => t.TId == tid).ToList();

            IList<EvalInfoExcelVM> list = new List<EvalInfoExcelVM>();
            var ques = _dbContext.Claim.ToList();
            foreach (var item in es)
            {
                var quesInfos = ScoreUtil.GetQuesInfos(item.Evals, ques);
                var dict = new Dictionary<string, string>();
                foreach (var q in quesInfos)
                {
                    var c = q.Claim;
                    var a = q.Answer;
                    dict.Add(c.Text, GetEvalLevel(a));
                }
                var ei = new EvalInfoExcelVM()
                {
                    Evals = dict,
                    StudentID = item.SId,
                    StudentName = item.Name,
                    CourseName = item.CName,
                };
                list.Add(ei);
            }
            return list;
        }

        public string GetEvalLevel(int level)
        {
            var r = level switch
            {
                1 => "非常好",
                2 => "还行",
                3 => "不满意",
                _ => "非常不满意",
            };
            return r;

        }
    }
}
